package com.example.hospitalapp;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {

    private EditText edtPhoneNumber, edtPassword;
    private Spinner spinnerRole;
    private Button btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        edtPhoneNumber = findViewById(R.id.edtPhoneNumber);
        edtPassword = findViewById(R.id.edtPassword);
        spinnerRole = findViewById(R.id.spinnerRole);
        btnLogin = findViewById(R.id.btnLogin);

        // 设置角色选择
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.roles, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerRole.setAdapter(adapter);

        // 登录按钮点击事件
        btnLogin.setOnClickListener(view -> {
            String phoneNumber = edtPhoneNumber.getText().toString();
            String password = edtPassword.getText().toString();
            String role = spinnerRole.getSelectedItem().toString();

            // 调用登录接口
            loginUser(phoneNumber, password, role);
        });
    }

    private void loginUser(String phoneNumber, String password, String role) {
        // 登录接口 URL，用于验证手机号和密码
        String loginUrl = role.equals("医生") ? "http://zhsj.autumnclouds.cn/doctor/login" : "http://zhsj.autumnclouds.cn/patient/login";

        // 创建请求参数
        JSONObject params = new JSONObject();
        try {
            params.put("phone", phoneNumber);
            params.put("password", password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 使用 Volley 请求进行登录
        ApiClient apiClient = new ApiClient(this);
        apiClient.postRequest(loginUrl, params, new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject result) {
                try {
                    // 根据 code 字段判断是否登录成功
                    int code = result.getInt("code");
                    if (code == 200) {
                        // 登录成功后，调用 queryUserInfo 查询更多信息
                        queryUserInfo(phoneNumber, role);
                    } else {
                        // 登录失败，处理错误信息
                        String errorMsg = result.getString("msg");
                        Log.e("LoginError", "Login failed: " + errorMsg);
                        showErrorDialog(errorMsg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showErrorDialog("登录失败，请重试");
                    // 异常处理
                }
            }
            @Override
            public void onFailure(String error) {
                showErrorDialog("登录失败，请重试");
            }
        });
    }
    private void showErrorDialog(String message) {
        // 使用 Toast 显示错误信息
        Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
    }
    // 根据角色和手机号查询病人或医生信息
    private void queryUserInfo(String phoneNumber, String role) {
        String url;
        JSONObject params = new JSONObject();
        try {
            params.put("phone", phoneNumber);  // 使用手机号查询对应的病人或医生
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 使用不同的接口查询病人或医生信息
        if (role.equals("病人")) {
            url = "http://zhsj.autumnclouds.cn/patient/query";  // 根据接口文档更改为正确的查询接口
        } else {
            url = "http://zhsj.autumnclouds.cn/doctor/query";  // 根据接口文档更改为正确的查询接口
        }

        // 使用 ApiClient 获取病人或医生信息
        ApiClient apiClient = new ApiClient(this);
        apiClient.postRequest(url, params, new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject result) {
                try {
                    // 从返回的 data 数组中获取数据
                    JSONArray dataArray = result.getJSONArray("data");

                    // 遍历 data 数组，确保获取正确的医生信息
                    for (int i = 0; i < dataArray.length(); i++) {
                        JSONObject data = dataArray.getJSONObject(i);

                        // 判断返回的医生手机号是否与登录时的手机号一致
                        if (data.getString("phoneNumber").equals(phoneNumber)) {
                            if (role.equals("病人")) {
                                // 获取病人信息
                                int patientId = data.getInt("patientId");
                                String name = data.getString("name");
                                String phone = data.getString("phoneNumber");
                                String email = data.getString("email");

                                // 创建 Patient 对象
                                Patient patient = new Patient(patientId, name, null, null, phone, email, null, "");

                                // 将病人信息传递到病人主页
                                Intent intent = new Intent(LoginActivity.this, PatientHomeActivity.class);
                                intent.putExtra("patient_info", patient);
                                startActivity(intent);

                            } else {
                                // 获取医生信息
                                int doctorId = data.getInt("doctorId");
                                String name = data.getString("name");
                                String specialty = data.getString("specialty");
                                String phone = data.getString("phoneNumber");
                                String room = data.getString("roomNumber");

                                // 创建 Doctor 对象
                                Doctor doctor = new Doctor(doctorId, name, specialty, phone, null, room, "");

                                // 将医生信息传递到医生主页
                                Intent intent = new Intent(LoginActivity.this, DoctorHomeActivity.class);
                                intent.putExtra("doctor_info", doctor);
                                startActivity(intent);
                            }
                            break;  // 找到对应的医生后退出循环
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(String error) {
                showErrorDialog("登录失败，请重试");
            }
        });
    }


}
